<?php


namespace App\Services;

use App\Exceptions\ApiException;
use App\Models\Sms;
use GuzzleHttp\Client;

class SmsService
{
    const MAX_SEND_DAY = 5;

    protected $client;

    public function __construct(Client $client)
    {
        $this->client = $client;
    }

    public function sendCode($phone, $code, $type)
    {
        if ($this->countSmsSendTimeToday($phone) >= self::MAX_SEND_DAY) {
            throw new ApiException('今日信息发送次数耗尽', 1);
        }
        $sms = Sms::query()->create([
            'code'      => $code,
            'status'    => Sms::STATUS['sended'],
            'send_time' => time(),
            'phone_number' => $phone,
            'type'         => $type,
        ]);
        $sendUrl = 'http://v.juhe.cn/sms/send';
        $requestParams = [
            'key'       => $_SERVER['SMS_APP_KEY'],
            'mobile'    => $phone,
            'tpl_id'    => '85973', // 短信模板ID 聚合控制台查看
            'tpl_value' => sprintf('#code#=%s', $code) // 模板变量
        ];

        $response = $this->client->get($sendUrl . http_build_query($requestParams));

        $resultStr = (string)$response->getBody();

        $result = json_decode($resultStr, true);

        if (isset($result['error_code']) && $result['error_code'] === 0) {
            $sms->update([
                'status' => Sms::STATUS['send_success'],
            ]);

            $sms->save();
        } else {
            throw new ApiException('网络错误', 1);
        }

        return true;
    }

    public function countSmsSendTimeToday($phone)
    {
        $count = Sms::query()->where('phone', $phone)
            ->where('send_time', 'like', date('Y-m-d', time()) . '%')
            ->whereIn('status', [
                Sms::STATUS['send_success'],
                Sms::STATUS['used'],
                Sms::STATUS['overdue'],
            ]);
        return $count;
    }
}
